package cn.bocai.pc.web.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.bocai.pc.model.BcDrawing;
import cn.bocai.pc.service.BcCollectService;
import cn.bocai.pc.service.BcDrawingService;
import cn.bocai.pc.service.BcLinktbleService;
import cn.bocai.pc.service.BcLinktypeService;
import cn.bocai.pc.service.BcPictureService;
import cn.bocai.pc.service.BcThumpicService;
import cn.bocai.pc.service.VariableService;
import cn.bocai.pc.util.UUIDUtils;

/**
 * 改方法为分页方法
 * 
 * @time 2015/07/04
 */
@Controller
@RequestMapping("/draws")
public class DrawingController {
	@Autowired
	private BcThumpicService bcThumpicService;
	@Autowired
	private BcLinktbleService bcLinktbleService;
	@Autowired
	private BcLinktypeService bcLinktypeService;
	@Autowired
	private BcCollectService bcCollectService;
	@Autowired
	private BcPictureService bcPictureService;
	@Autowired
	private VariableService variableService;
	@Autowired
	private BcDrawingService bcDrawingService;

	// 图纸页面后台保存的跳转
	@RequestMapping("/drawSave.do")
	public String delectThumOne(HttpServletRequest request, Model m) {
		return "baPage/drawing/drawSave";
	}

	// 批量新增类型数据
	@RequestMapping("/batchSave.do")
	public void batchSave(HttpServletRequest request,HttpServletResponse response, Model m,String year) throws Exception {
		bcDrawingService.clearData(year);//先清空数据，在保存
		
		StringBuffer buffer = new StringBuffer();// 存储重复名称数据
		StringBuffer ZNName = new StringBuffer();// 存储名称中出现中文的信息
		StringBuffer abnormal = new StringBuffer();// 异常数据
		String textarea = request.getParameter("textarea").trim();// 获取文本域数据
		String[] splits = textarea.split("#");// 切割数据
		// 中文返回的编码
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		for (int x = 0; x < splits.length; x++) {
			boolean deposit=true;//用来判断数据是否要保存的
			String[] splitSon = splits[x].split("\\|");
			String name = splitSon[0].trim();
			//如果大于三个或者小于2的时候表示就有异常
			if(splitSon.length>3||splitSon.length<2){
				if (abnormal.length() > 0) {
					abnormal.append("," + name);
				} else {
					abnormal.append(name);
				}
				continue;  
			}
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("picname", name);
			map.put("year", year);
			BcDrawing selectNamecol = bcDrawingService.checkoutName(map);// 根据编码唯一性查询
			if (null != selectNamecol && !"".equals(selectNamecol)) {
				deposit=false;
				if (buffer.length() > 0) {
					buffer.append("," + name);
				} else {
					buffer.append(name);
				}
			}
			// 监测中文
			boolean variable = true;
			for (int i = 0; i < name.length(); i++) {
				boolean matches = name.substring(i, i + 1).matches("[\\u4e00-\\u9fa5]+");// 监测是否有中文
				if (matches) {
					variable = false;
					deposit=false;
					break;
				}
			}
			if (!variable) {
				if (ZNName.length() > 0) {
					ZNName.append("," + name);
				} else {
					ZNName.append(name);
				}
			}
			
			if(deposit){
				BcDrawing recObject = bcDrawingService.reciprocalOne(year);// 获取最后一条数据的对象值
				int cacheOrder = 0;
				// 将获取到前台的用户要求的显示的第几页数据转化为整型类型数据
				if (recObject != null && !recObject.equals("")) {
					cacheOrder = recObject.getFeatureSort();// 缓存排序
				}
				  BcDrawing bcThumpic = new BcDrawing();
					bcThumpic.setId(UUIDUtils.getUUID32());
					bcThumpic.setPicname(name);
					bcThumpic.setDesctibe(splitSon[1]);
					bcThumpic.setYear(year);
					bcThumpic.setUrladdress("/" + year + "/" + splitSon[0].trim()+ ".jpg");
					bcThumpic.setHtmlAddress("/" + year + "/" + splitSon[0].trim()+ ".html");
					if (splitSon.length > 2) {// 如果有排序值就使用自己的
						try{
							bcThumpic.setFeatureSort(Integer.parseInt(splitSon[2]));
						}catch (Exception e) {
							e.printStackTrace();
							if (abnormal.length() > 0) {
								abnormal.append("," + name);
							} else {
								abnormal.append(name);
							}
							continue;  
						}
						
						// 当使用自己的排序值的时候也需要查询一遍
						recObject = bcDrawingService.reciprocalOne(year);// 获取最后一条数据的对象值
						// 将获取到前台的用户要求的显示的第几页数据转化为整型类型数据
						if (recObject != null && !recObject.equals("")) {
							cacheOrder = recObject.getFeatureSort();// 缓存排序
						}
					} else {
						cacheOrder = cacheOrder + 10;
						bcThumpic.setFeatureSort(cacheOrder);
					}
					bcDrawingService.addInsert(bcThumpic);
			}
		}
		// 当大于0的时候表示有重复的
		if (buffer.length() > 0 || ZNName.length() > 0||abnormal.length()>0) {
			out.print(buffer + "_" + ZNName+"_"+abnormal);
			/* m.addAttribute("returnVal",buffer); */
		} else {
			out.print("success");
		}
	}

	/**
	 * 重新生成静态模板
	 * 
	 * @throws IOException
	 */
	@RequestMapping("/returnRefresh.do")
	public void returnRefresh(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String parYears = request.getParameter("year");// 获取年份
		bcDrawingService.scanStorageByThumpic(parYears);
	}

	/**
	 * 全年图纸后台基本操作
	 */
	@RequestMapping("/drawBasic.do")
	public String drawBasic(HttpServletRequest request, Model m) {
		// 到数据字典去查询出对应的值
		/*String year = variableService.selectVariable("year");// 获取字典中的年份*/	
    	String draUrl = variableService.selectVariable("DRA_UEL");// /drawPic
		String baUrl = variableService.selectVariable("BA_URL");// http://localhost:8081
		List<String> pulDownYear = bcDrawingService.pulDownYear();// 所有年份集合
		
		String year = bcDrawingService.pulDownYearOne();// 所有年份中最新的年份
		String _cs = request.getParameter("year");
		// 1:获取传输过来的年份
		// 将获取到前台的用户要求的图片类型进行赋值
		if (_cs != null && !_cs.trim().equals("")) {
			try {
				year = _cs;
			} catch (Exception e) {
				// 不处理
			}
		}

		String method = request.getMethod();// 获取请求的类型
		String parKeyword = request.getParameter("queryValue");// 获取搜索框传输过来的值

		if (parKeyword != null && !parKeyword.trim().equals("")) {
			m.addAttribute("retColour", _cs);// 将年份的值返回
			// 如果是post请求是不需要进行中文转码的，但是如果是get请求那就需要中文转码了
			if ("GET".equalsIgnoreCase(method)) {
				try {
					parKeyword = new String(parKeyword.getBytes("ISO-8859-1"),"utf-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}// 中文get形式传输需要转码
			}
		}

		String _ps = request.getParameter("pageSize");
		// 1:定义每页显示多少行记录
		int pageSize = 15;
		// 将获取到前台的用户要求的显示的第几页数据转化为整型类型数据
		if (_ps != null && !_ps.trim().equals("")) {
			try {
				pageSize = Integer.parseInt(_ps);
			} catch (Exception e) {
				// 不处理
			}
		}
		// 2:获取用户要求显示第几页
		String _cp = request.getParameter("currentPageNumber");
		// 默认等于第一页
		int currentPage = 1;
		// 将获取到前台的用户要求的显示的第几页数据转化为整型类型数据
		if (_cp != null && !_cp.trim().equals("")) {
			try {
				currentPage = Integer.parseInt(_cp);
			} catch (Exception e) {
				// 不处理
			}
		}
		try {
			// 查询出一共多少条数
			int rowCount = 0;
			if (parKeyword != null && !parKeyword.trim().equals("")) {
				Map<String, Object> searCount = new HashMap<String, Object>();
				searCount.put("parKeyword", parKeyword);// 传递过来的参数
				searCount.put("year", year);// 传递过来的年份
				rowCount = bcDrawingService.searAllRowAll(searCount);// 查询搜索的时候的值总行数
			} else {
				rowCount = bcDrawingService.searRowAll(year);// 查询出总的数据的行数
			}
			// 4:计算一共分多少页
			int pageCount = rowCount / pageSize
					+ (rowCount % pageSize == 0 ? 0 : 1);
			// 判断当前页面要求页数是否已经大于pageCount（总页数）最大页数，如果大于就拿总页数否则就拿页面要求的
			currentPage = (currentPage > pageCount ? pageCount : currentPage);
			// 判断
			currentPage = (currentPage <= 0 ? 1 : currentPage);
			// 5:计算从哪一行开始查询
			int start = (currentPage - 1) * pageSize;
			// 6:查询出指定行数的数据
			Map<String, Object> searMap = new HashMap<String, Object>();
			searMap.put("start", start);
			searMap.put("pageSize", pageSize);
			searMap.put("year", year);

			List<BcDrawing> searchList = null;
			if (parKeyword != null && !parKeyword.trim().equals("")) {
				searMap.put("parKeyword", parKeyword);
				searchList = bcDrawingService.searDataPic(searMap);// 查询搜索的分页
			} else {
				searchList = bcDrawingService.baGetSelectsearch(searMap);
			}

			m.addAttribute("draUrl", draUrl);
			m.addAttribute("baUrl", baUrl);
			m.addAttribute("listYear", pulDownYear);// 所有年份集合

			// 封装数据将传到前台数据
			m.addAttribute("datas", searchList);// 查询出的数据
			m.addAttribute("pageCount", pageCount);// 一个分多少页
			m.addAttribute("currentPage", currentPage);// 当前页数
			m.addAttribute("rowCount", rowCount);// 一共多少条数据
			m.addAttribute("pageSize", pageSize);// 每页显示的条数
			m.addAttribute("yearsType", year);// 颜色标示
			m.addAttribute("queryValue", parKeyword);// 获取到的查询值

			// 以下计算开始显示的页码和结束显示的页码
			int showCount = 10; // 页面显示多少个页码
			int showStart = 0; //
			int showEnd = 0; //
			// 如果总页码还不够15页
			if (pageCount <= showCount) {
				showStart = 1;
				showEnd = pageCount;// 那么结束页面就等于总页码
			} else {// 分页显示页码
				if (currentPage <= (showCount / 2)) {
					showStart = 1;
					showEnd = showCount;
				} else {
					showStart = currentPage - (showCount / 2 - 1);
					showEnd = showStart + (showCount - 1);
				}
				// 如果showEnd已经超出总页面
				if (showEnd >= pageCount) { // 最后的页面大于等于总页码
					showEnd = pageCount;
					showStart = showEnd - (showCount - 1);
				}
			}
			m.addAttribute("showStart", showStart);
			m.addAttribute("showEnd", showEnd);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return "baPage/drawing/drawBasic";
	}

	/**
	 * 批量删除
	 * 
	 * @throws IOException
	 */
	@RequestMapping("/delectAll.do")
	public void delectAll(HttpServletRequest request,
			HttpServletResponse response, Model m) throws IOException {
		String[] id = request.getParameter("uuid").split(",");
		for (int i = 0; i < id.length; i++) {
			bcDrawingService.delectAlone(id[i]);
		}
		response.getWriter().print("succeed");
	}

	/**
	 * 删除单挑数据
	 * 
	 * @throws IOException
	 */
	@RequestMapping("/delectAlone.do")
	public void delectAlone(HttpServletRequest request,
			HttpServletResponse response, Model m) throws IOException {
		String id = request.getParameter("uuid");
		int delectAlone = bcDrawingService.delectAlone(id);
		response.getWriter().print(1 == delectAlone ? "succeed" : "Failure");
	}

	/**
	 * 校验全年图纸的注册名是否被使用
	 * 
	 * @throws IOException
	 */
	@RequestMapping("/checkoutName.do")
	public void checkoutName(HttpServletRequest request,
			HttpServletResponse response, Model m) throws IOException {
		response.setContentType("text/html;charset=utf-8");
		String year = request.getParameter("year");
		String name = request.getParameter("code");
		boolean variable = true;
		String returndate = "";// 返回数据
		for (int i = 0; i < name.length(); i++) {
			boolean matches = name.substring(i, i + 1).matches(
					"[\\u4e00-\\u9fa5]+");
			if (matches) {
				variable = false;
				break;
			}
		}
		if (variable) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("picname", name);
			map.put("year", year);
			BcDrawing checkoutName = bcDrawingService.checkoutName(map);
			
			returndate="succend";//表示没有重复
			if(null!=checkoutName){
		    returndate="defeated";//有重复
			} 
		
		} else {
			returndate = "zh";// 有中文
		}
		response.getWriter().print(returndate);
	}
	
	
	 /**
	 *全年图纸数据保存
     * @throws IOException 
	 */
	@RequestMapping("/addPicture.do")
	public void addPicture(HttpServletRequest request,HttpServletResponse response,Model m,BcDrawing bcDrawing) throws IOException{
		bcDrawing.setId(UUIDUtils.getUUID32());
		bcDrawing.setHtmlAddress("/"+ bcDrawing.getYear() + "/" +bcDrawing.getPicname()+ ".html");
		int addInsert=bcDrawingService.addInsert(bcDrawing);
		response.getWriter().print(addInsert);
	}
	
	 /**
	 *全年图纸修改
     * @throws IOException 
	 */
	@RequestMapping("/updateAlone.do")
	public void updateAlone(HttpServletRequest request,HttpServletResponse response,Model m,BcDrawing bcDrawing) throws IOException{
		bcDrawing.setHtmlAddress("/"+ bcDrawing.getYear() + "/" +bcDrawing.getPicname()+ ".html");
		
		int updateAlone = bcDrawingService.updateAlone(bcDrawing);
		response.getWriter().print(updateAlone);
	}
	
	/**
	 *清空数据
     * @throws IOException 
	 */
	@RequestMapping("/clearData.do")
	public void clearData(HttpServletRequest request,HttpServletResponse response,Model m,String year) throws IOException{
		int clearData = bcDrawingService.clearData(year);
		response.getWriter().print(clearData);
	}
	
	/**
	 *全年图纸数据回显
     * @throws IOException 
	 */
	@RequestMapping("/returnBatch.do")
	    public @ResponseBody List<BcDrawing> listSubCates(String year){
	         List<BcDrawing> cs = bcDrawingService.selectAllDraw(year);
	        return cs;
	   }
}
